Understanding Authentication and Authorization in Web Applications
Course: Advanced Java Training
Topic: Understanding Authentication and Authorization in Web Applications
Course Link: Advanced Java Training Course – JustAcademy
Demo Link: Register for a Course Demo
Official Website: JustAcademy
1. Introduction to Authentication and Authorization
Authentication and authorization are fundamental security mechanisms used to protect web applications, user accounts, and confidential information. Authentication verifies the identity of a user, while authorization determines which resources and operations the user is permitted to access.
In Advanced Java web applications, these mechanisms can be implemented using Servlets, JSP, HTTP sessions, Servlet filters, JDBC, deployment descriptors, and security frameworks.
For example, when a user logs into an employee management portal, authentication verifies the user's credentials. After successful login, authorization determines whether that user can view an employee profile, modify records, or access administrative functions.
Learning Objectives
- Understand authentication and authorization concepts.
- Identify the differences between authentication and authorization.
- Learn common authentication methods used in Java web applications.
- Understand session-based and token-based authentication.
- Implement login and logout workflows using Servlets.
- Apply role-based and resource-level authorization.
- Protect application resources using Servlet filters and security constraints.
- Understand password security, session management, and access-control vulnerabilities.
- Test authentication and authorization mechanisms effectively.
2. Understanding Authentication
Authentication is the process of verifying the identity of a person, application, or system. A web application typically authenticates a user before granting access to protected resources.
2.1 Common Authentication Factors
| Factor |
Description |
Example |
| Something You Know |
Information known to the user. |
Password or PIN. |
| Something You Have |
A physical or digital item controlled by the user. |
Security key or authenticator app. |
| Something You Are |
A biometric characteristic. |
Fingerprint or facial recognition. |
Multi-factor authentication (MFA) combines two or more distinct authentication factors. It provides additional protection if one factor, such as a password, is compromised.
2.2 Common Authentication Methods
- Username and password: The user supplies credentials that the application verifies against securely stored account information.
- Multi-factor authentication: The user must provide an additional authentication factor.
- Session-based authentication: The server maintains authentication state associated with a user's session.
- Token-based authentication: The client presents a valid token when requesting protected resources.
- Single Sign-On (SSO): A trusted identity provider authenticates users for access to multiple applications.
- Certificate-based authentication: A user or system proves possession of a trusted cryptographic credential.
2.3 Example of Authentication
Consider an online learning platform. A student enters a username and password. The server checks the submitted credentials against the stored account information. If verification succeeds, the application establishes an authenticated session or issues an appropriate token.
If verification fails, the application rejects the login attempt without revealing sensitive details about the account or authentication process.
3. Understanding Authorization
Authorization determines whether an authenticated user has permission to access a resource or perform an operation. Permissions may depend on the user's role, assigned privileges, record ownership, department, or other business rules.
3.1 Examples of Authorization
- A student can view their own course progress but cannot modify another student's records.
- An employee can access personal information but cannot manage administrator accounts.
- A manager can approve requests within their assigned department.
- An editor can create and update content but cannot change system security settings.
- An administrator can perform explicitly authorized administrative operations.
3.2 Authentication vs. Authorization
| Feature |
Authentication |
Authorization |
| Purpose |
Verifies identity. |
Determines permitted access. |
| Main Question |
Who are you? |
What are you allowed to do? |
| Typical Timing |
During login or identity verification. |
When accessing a protected resource or performing an operation. |
| Input |
Credentials, authentication factors, or identity assertions. |
Identity, roles, permissions, and resource policies. |
| Failure Example |
Invalid credentials. |
Authenticated user lacks the required permission. |
| Typical Result |
Authentication is rejected or requested. |
The requested operation is denied. |
Authentication and authorization work together, but they solve different security problems. A successfully authenticated user should not automatically receive access to every resource in the application.
4. How Authentication and Authorization Work Together
A secure web application typically verifies a user's identity, establishes authentication state, checks permissions, and processes the request only when access is allowed.
User Opens Application
|
v
User Submits Credentials
|
v
Server Verifies Identity
|
+----+----+
| |
v v
Invalid Valid
| |
v v
Reject Login Establish Session or Token
|
v
Request Protected Resource
|
v
Check Permissions
|
+----+----+
| |
v v
Allowed Denied
| |
v v
Process Request Reject Access
Step-by-Step Workflow
- The user opens the application and requests a protected resource.
- The application requests authentication if the user is not already authenticated.
- The server verifies the supplied credentials through a trusted authentication mechanism.
- After successful authentication, the application establishes a secure session or issues an appropriate token.
- The user requests a page, API endpoint, or business operation.
- The server evaluates the user's permissions and any resource-specific access rules.
- The application performs the requested operation only if authorization succeeds.
5. HTTP Status Codes Related to Authentication and Authorization
| Status Code |
Meaning |
Typical Situation |
| 200 OK |
Request succeeded. |
The user is permitted to access the requested resource. |
| 302 Found |
Temporary redirect. |
A traditional web application redirects a user to a login page. |
| 401 Unauthorized |
Valid authentication is missing or unacceptable. |
A protected API request lacks valid credentials. |
| 403 Forbidden |
The requested operation is refused. |
An authenticated user lacks the required permission. |
| 404 Not Found |
The resource is unavailable or does not exist. |
A nonexistent page or a resource intentionally concealed from an unauthorized user. |
Important: HTTP 401 generally indicates an authentication problem, while HTTP 403 generally indicates an authorization problem. Applications may return 404 instead of 403 when disclosing a resource's existence could create a security risk.
6. Authentication Technologies in Advanced Java
| Technology |
Purpose |
| Servlets |
Process login requests and coordinate application operations. |
| JSP |
Render login forms and user-facing pages. |
| HttpSession |
Maintain server-side session state. |
| Servlet Filters |
Intercept requests for authentication and access-control checks. |
| JDBC |
Retrieve account information from a database. |
| web.xml |
Configure deployment settings and declarative security constraints. |
| Spring Security |
Provide authentication and authorization features in Spring applications. |
6.1 Basic Login Workflow
- Display a login form over HTTPS.
- Accept submitted credentials through a suitable HTTP POST endpoint.
- Validate the required fields and request format.
- Retrieve the corresponding account using a parameterized database query.
- Verify the submitted password against the stored password hash using an appropriate password-hashing library.
- Check account status and any additional authentication requirements.
- Establish the authenticated session or issue a token.
- Redirect the user to an allowed destination.
Passwords must never be stored as plaintext. Use a suitable password-hashing algorithm, such as Argon2id, bcrypt, or PBKDF2, with appropriate parameters and a reputable implementation.
7. Creating a Login Form Using JSP
JavaServer Pages can be used to create a login interface. The form collects the username and password and submits them to a server-side authentication endpoint.
7.1 JSP Login Form Example
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Login</title>
</head>
<body>
<h2>Login to Your Account</h2>
<form action="${pageContext.request.contextPath}/login"
method="post">
<label for="username">Username:</label>
<input type="text" id="username"
name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password"
name="password" required>
<br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
7.2 Explanation
- The form collects the user's credentials.
- The POST method submits the form data in the request body rather than placing credentials in the URL.
- The form action directs the request to the application's login endpoint.
- HTML validation improves usability but does not replace server-side validation.
- HTTPS protects credentials during transmission.
Security note: A production login form should include suitable CSRF protection, rate limiting, secure password verification, and safe handling of failed authentication attempts. The form itself does not authenticate a user.
8. Processing Login Requests Using a Servlet
A login servlet receives credentials and delegates verification to a trusted authentication service. After successful verification, the application establishes authenticated state and redirects the user to an appropriate page.
8.1 Example Login Servlet
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private AuthenticationService authenticationService;
@Override
public void init() throws ServletException {
// Obtain the authentication service through
// the application's dependency configuration.
authenticationService = AuthenticationServiceProvider.get();
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null || username.isBlank()
|| password == null || password.isEmpty()) {
response.sendError(
HttpServletResponse.SC_BAD_REQUEST,
"Invalid login request"
);
return;
}
AuthenticatedUser user =
authenticationService.authenticate(username, password);
if (user == null) {
response.sendError(
HttpServletResponse.SC_UNAUTHORIZED,
"Unable to authenticate"
);
return;
}
HttpSession session = request.getSession();
request.changeSessionId();
session.setAttribute("loggedInUserId", user.getId());
response.sendRedirect(
request.getContextPath() + "/user/dashboard"
);
}
}
Explanation:
- The servlet retrieves the submitted username and password.
- It performs basic request validation.
- The authentication service verifies the credentials.
- If verification fails, the servlet rejects the request.
- If verification succeeds, the servlet establishes authenticated session state and redirects the user.
Implementation note: AuthenticationService, AuthenticationServiceProvider, and AuthenticatedUser represent application-specific classes and must be implemented. The example assumes a configured authentication service, a valid Servlet container, and appropriate CSRF protection.
In production, use the application's established dependency-injection mechanism. Ensure session-ID rotation is supported by the deployed Servlet version, and do not trust roles or identities supplied directly by the client.
9. Managing User Sessions
HTTP is stateless, meaning individual requests do not automatically share authentication information. An HTTP session can maintain server-side state associated with a user across multiple requests.
9.1 Creating and Accessing a Session
HttpSession session = request.getSession();
session.setAttribute("loggedInUserId", userId);
Object storedUserId =
session.getAttribute("loggedInUserId");
9.2 Session Security Best Practices
- Use HTTPS for all authenticated requests.
- Regenerate the session identifier after authentication.
- Configure session cookies with Secure and HttpOnly attributes.
- Use an appropriate SameSite cookie policy.
- Set reasonable inactivity timeouts.
- Invalidate the session during logout.
- Never store plaintext passwords in session attributes.
- Ensure only trusted server-side authentication logic establishes authenticated state.
9.3 Example Logout Servlet
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.sendRedirect(
request.getContextPath() + "/login.jsp"
);
}
}
Logout should use a protected POST request with CSRF protection where applicable. If the application uses additional authentication tokens, those credentials may require separate revocation or invalidation.
10. Implementing Authentication Checks with Servlet Filters
A Servlet filter intercepts incoming requests and can verify whether a user is authenticated before allowing access to protected resources.
10.1 Example Authentication Filter
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebFilter("/user/*")
public class UserAuthenticationFilter implements Filter {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req =
(HttpServletRequest) request;
HttpServletResponse res =
(HttpServletResponse) response;
HttpSession session = req.getSession(false);
if (session == null ||
session.getAttribute("loggedInUserId") == null) {
res.sendError(
HttpServletResponse.SC_UNAUTHORIZED,
"Authentication required"
);
return;
}
chain.doFilter(request, response);
}
}
The filter protects URLs matching /user/*. It checks for an expected server-managed session attribute before allowing the request to continue.
This is an educational example rather than a complete security framework. The login workflow must set the session attribute only after successful authentication. Authorization checks are still necessary for administrative operations and individual records.
11. Role-Based Access Control (RBAC)
Role-Based Access Control organizes permissions around roles. Users receive roles based on their responsibilities, and each role is associated with specific authorized actions.
11.1 Common Application Roles
| Role |
Typical Permissions |
| GUEST |
View public pages and permitted public content. |
| USER |
View and manage the user's own permitted account information. |
| EDITOR |
Create and modify assigned content. |
| MANAGER |
Approve operations within assigned responsibilities. |
| ADMIN |
Perform explicitly authorized administrative operations. |
11.2 Checking Roles in a Servlet
if (request.isUserInRole("ADMIN")) {
// Perform an operation permitted for administrators.
} else {
response.sendError(
HttpServletResponse.SC_FORBIDDEN,
"Access denied"
);
return;
}
The isUserInRole() method checks role membership through the configured Servlet security system. The container must be configured to authenticate the user and map the appropriate roles.
11.3 Benefits of RBAC
- Centralizes permission management.
- Reduces repeated authorization logic.
- Makes user responsibilities easier to understand.
- Supports security audits and permission reviews.
- Helps enforce the principle of least privilege.
12. Declarative Security Using web.xml
Declarative security defines resource-access requirements in the application's deployment descriptor. The Servlet container enforces the configured constraints according to the authentication mechanism and role mappings.
12.1 Example: Protecting Administrative URLs
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin Area</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<security-role>
<role-name>ADMIN</role-name>
</security-role>
12.2 Explanation
/admin/* identifies the protected URL pattern.
ADMIN specifies the logical role permitted to access the resources.
CONFIDENTIAL requires a protected transport, normally HTTPS, when supported and configured by the deployment environment.
- The container must have authentication and role mappings configured.
This configuration does not create user accounts or configure a complete login system by itself. The authentication mechanism and role mappings must also be configured. Review the security constraints to ensure that sensitive HTTP methods and operations are not left unprotected.
13. Resource-Level Authorization
Role-based authorization is useful, but some applications require more specific checks. Resource-level authorization verifies whether a user can access a particular record or object.
13.1 Example: Protecting Employee Records
Suppose an employee portal allows employees to view their own records. The application must verify that the requested record belongs to the authenticated user or that the user has a separate permission to access it.
public boolean canViewEmployee(
AuthenticatedUser currentUser,
Employee employee) {
if (currentUser == null || employee == null) {
return false;
}
if (currentUser.hasPermission("EMPLOYEE_READ_ALL")) {
return true;
}
return currentUser.getId().equals(employee.getUserId());
}
This example assumes application-specific user and employee classes. In a production application, enforce the authorization rule consistently in the service or data-access layer so every entry point applies the same policy.
13.2 Why Resource-Level Checks Matter
- Prevent users from viewing another user's private information.
- Reduce insecure direct object reference (IDOR) vulnerabilities.
- Enforce ownership and organizational boundaries.
- Prevent unauthorized modifications to protected records.
14. Password Security and Account Protection
Password security is a critical part of authentication. Applications must protect credentials during transmission and prevent stored passwords from being exposed in readable form.
14.1 Password Security Best Practices
- Store password hashes rather than plaintext passwords.
- Use an established password-hashing algorithm such as Argon2id, bcrypt, or PBKDF2 with appropriate parameters.
- Use unique salts through a reputable password-hashing library.
- Never log passwords or include them in error messages.
- Apply rate limiting to repeated login attempts.
- Use secure password-reset procedures with short-lived, single-use tokens.
- Consider multi-factor authentication for sensitive accounts and operations.
- Use generic login failure messages where appropriate to reduce account enumeration.
14.2 Prepared Statements for User Lookup
String sql =
"SELECT id, password_hash, status FROM users WHERE username = ?";
try (java.sql.PreparedStatement statement =
connection.prepareStatement(sql)) {
statement.setString(1, username);
try (java.sql.ResultSet result =
statement.executeQuery()) {
if (result.next()) {
// Retrieve the stored password hash and account status.
// Verify the submitted password using a suitable
// password-hashing library.
}
}
}
Prepared statements separate query structure from user-supplied values and help prevent SQL injection. Password verification must use an appropriate password-hashing library rather than direct plaintext string comparison.
15. Token-Based Authentication
Token-based authentication allows a client to present a token when requesting access to a protected resource. It is commonly used in REST APIs, mobile applications, and distributed systems.
15.1 Token Authentication Workflow
- The client submits credentials or authenticates through a trusted identity provider.
- The authentication system verifies the user's identity.
- The system issues a token containing the required identity and authorization claims.
- The client sends the token through the expected authentication mechanism.
- The server validates the token's authenticity, expiry, issuer, audience, and relevant claims.
- The application checks permissions before processing the requested operation.
15.2 JSON Web Tokens (JWT)
A JSON Web Token is a compact format used to carry claims between parties. A signed JWT provides integrity protection, but its contents are not automatically encrypted. Avoid placing confidential information in readable token claims.
15.3 Token Security Best Practices
- Validate the token signature and required claims.
- Allow only explicitly configured signing algorithms.
- Use appropriate token expiration times.
- Protect tokens in transit and at rest.
- Implement revocation or rotation where required.
- Never trust unvalidated token data.
- Assess browser token storage carefully, including XSS and CSRF risks.
16. Common Authentication and Authorization Vulnerabilities
| Vulnerability |
Description |
Prevention |
| Brute-Force Attacks |
Repeated attempts to guess credentials. |
Rate limiting, monitoring, and appropriate account protections. |
| Credential Stuffing |
Previously leaked credentials are tested against other accounts. |
MFA, rate limits, and compromised-password detection. |
| Session Fixation |
An attacker attempts to make a victim use a known session identifier. |
Regenerate session identifiers after authentication. |
| Session Hijacking |
An attacker obtains and reuses another user's session. |
HTTPS, protected cookies, and secure session management. |
| Broken Access Control |
Users access resources or actions beyond their permissions. |
Enforce server-side authorization on every protected operation. |
| IDOR |
A user changes a record identifier to access another user's data. |
Check resource ownership and permissions on the server. |
| Privilege Escalation |
A user gains higher privileges than intended. |
Validate role assignments and protect privileged operations. |
| CSRF |
A browser submits an unwanted authenticated request. |
Use CSRF tokens and appropriate cookie policies. |
| SQL Injection |
Untrusted input changes database query behavior. |
Use prepared statements and parameterized queries. |
17. Testing Authentication and Authorization
Security testing should verify both successful access and denied requests. Checks must be performed on the server-side endpoints and business operations, not only in the user interface.
| Test Case |
Action |
Expected Result |
| Valid login |
Submit correct credentials for an active account. |
Authentication succeeds and a secure session or token is established. |
| Invalid login |
Submit incorrect credentials. |
Authentication fails without exposing sensitive account details. |
| Unauthenticated access |
Request a protected URL without logging in. |
Access is denied or authentication is required. |
| Unauthorized role |
Open an admin page as a normal user. |
The server denies access. |
| Record ownership |
Attempt to access another user's record. |
The server denies access unless explicit permission exists. |
| Session logout |
Log out and retry a protected request. |
The invalidated session no longer grants access. |
| Session fixation |
Check session identifiers before and after login. |
The application prevents reuse of a pre-authentication session ID for authenticated access. |
| SQL injection |
Submit unexpected SQL-like input. |
Input cannot change query structure. |
| Token validation |
Submit expired, malformed, or incorrectly signed tokens. |
The server rejects invalid tokens. |
18. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Users cannot log in |
Incorrect credential verification or account configuration. |
Review authentication logic, stored hashes, and account status. |
| Authenticated users receive 401 |
Session or token is missing, expired, or not recognized. |
Check authentication state and the configured security mechanism. |
| Users receive 403 unexpectedly |
Incorrect role mapping or insufficient permissions. |
Review role assignments and authorization rules. |
| Protected pages are accessible without login |
Missing or incorrect filter mappings or security constraints. |
Review protected URL patterns and server-side checks. |
| Admin functions are accessible to normal users |
Authorization relies on the UI or client-supplied roles. |
Enforce trusted server-side authorization. |
| Users can access other users' records |
Resource ownership is not validated. |
Check access to each requested record in the service layer. |
| Logout does not end access |
Session was not invalidated or another token remains valid. |
Invalidate the session and handle other authentication state appropriately. |
| Login causes database errors |
Incorrect query, schema, or connection configuration. |
Inspect protected logs and verify parameterized queries. |
19. Security Best Practices Checklist
- Use HTTPS for login, authenticated sessions, and sensitive operations.
- Store password hashes using a suitable password-hashing algorithm.
- Apply multi-factor authentication where appropriate.
- Regenerate session identifiers after authentication.
- Configure secure session cookies and appropriate expiration policies.
- Invalidate sessions during logout.
- Use centralized authorization policies and the principle of least privilege.
- Validate access to individual records and sensitive operations.
- Protect administrative endpoints and relevant HTTP methods.
- Use prepared statements for database queries.
- Apply CSRF protection to relevant state-changing requests.
- Keep passwords, tokens, and sensitive session data out of logs.
- Use safe error messages where detailed responses could expose sensitive information.
- Test both permitted and denied access scenarios.
- Review permissions regularly and remove unnecessary privileges.
20. Practical Exercises
- Create a Login Page: Build a JSP login form and submit credentials to a Servlet using POST.
- Implement Authentication: Create an authentication service that verifies passwords using an appropriate password-hashing library.
- Manage Sessions: Establish a session after login, rotate the session identifier, and implement logout.
- Protect User URLs: Create a Servlet filter that blocks unauthenticated requests to a protected URL pattern.
- Implement RBAC: Create USER and ADMIN roles and restrict administrative operations.
- Secure Employee Records: Ensure employees can view their own records while administrators receive only explicitly authorized access.
- Test Authorization: Verify that users cannot access restricted URLs or records by changing request parameters.
- Improve Security: Add login rate limiting, secure error handling, and suitable CSRF protection.
Mini Project: Secure Employee Management Portal
Develop a Java web application with employee login, profile management, administrator operations, and logout functionality. Store account information securely, protect sessions, implement role-based authorization, and validate access to individual employee records.
Test the application with normal users, administrators, invalid credentials, expired sessions, and unauthorized requests. Document the security rules and expected results for each test case.
21. Interview Questions and Answers
Q1. What is authentication?
Answer: Authentication verifies the identity of a user or system using credentials, tokens, certificates, or other authentication factors.
Q2. What is authorization?
Answer: Authorization determines which resources and operations an authenticated identity is permitted to access.
Q3. What is the main difference between authentication and authorization?
Answer: Authentication verifies identity, while authorization evaluates permissions. Successful authentication does not automatically grant access to every resource.
Q4. What is session-based authentication?
Answer: It is a mechanism in which the server maintains authentication state associated with a session and recognizes subsequent requests using the session identifier.
Q5. What is role-based access control?
Answer: RBAC assigns permissions through roles, such as USER, EDITOR, and ADMIN, to simplify access management.
Q6. What is the purpose of a Servlet filter?
Answer: A Servlet filter intercepts requests and responses and can enforce authentication checks, authorization policies, request validation, and logging.
Q7. How can a Java web application restrict administrative pages?
Answer: It can use Servlet security constraints, container-managed roles, programmatic security, or a framework such as Spring Security.
Q8. What is the difference between HTTP 401 and HTTP 403?
Answer: HTTP 401 indicates that valid authentication is missing or unacceptable. HTTP 403 indicates that the requested operation is refused, commonly because the user lacks permission.
Q9. What is session fixation?
Answer: Session fixation is an attack in which an attacker attempts to make a victim authenticate using a known session identifier. Regenerating the session ID after authentication helps prevent it.
Q10. Why should passwords be hashed?
Answer: Password hashing helps protect stored credentials if a database is exposed. Passwords should be hashed with an appropriate password-hashing algorithm rather than stored as plaintext.
Q11. What is JWT authentication?
Answer: JWT-based authentication uses JSON Web Tokens to carry claims about an identity. The server must validate the token and its required claims before trusting them.
Q12. What is the principle of least privilege?
Answer: It means granting users and application components only the permissions required for their assigned responsibilities.
Q13. Why is server-side authorization important?
Answer: Client-side restrictions can be bypassed. Server-side authorization ensures that every protected operation verifies permissions before execution.
Q14. What is an IDOR vulnerability?
Answer: Insecure Direct Object Reference occurs when a user can access another user's resource by changing an identifier because the application fails to verify authorization.
Q15. How does multi-factor authentication improve security?
Answer: MFA requires more than one distinct type of authentication factor, making a stolen password alone less likely to provide account access.
22. Quick Revision Notes
- Authentication: Verifies identity.
- Authorization: Determines access permissions.
- HttpSession: Maintains server-side session state.
- Servlet Filter: Intercepts requests and responses for shared security checks.
- RBAC: Organizes permissions around roles.
- HTTP 401: Authentication is missing or invalid.
- HTTP 403: Access is forbidden.
- Password Hashing: Protects stored passwords against direct disclosure.
- Session Rotation: Helps mitigate session-fixation attacks.
- Least Privilege: Grants only necessary permissions.
- Resource-Level Authorization: Checks whether a user may access a specific record.
- Security Testing: Verifies both successful access and denied requests.
23. Conclusion
Authentication and authorization are essential for protecting Java web applications, user accounts, confidential records, and administrative operations. Authentication establishes identity, while authorization determines what that identity is permitted to do.
By combining secure password verification, session management, Servlet filters, role-based access control, resource-level permission checks, and comprehensive testing, developers can build more reliable and secure web applications.
Security must be enforced on the server for every protected operation. Hiding buttons, restricting navigation, or trusting client-supplied roles is not sufficient to prevent unauthorized access.
Continue Learning with JustAcademy
Explore the Advanced Java Training Course to continue learning Java web development, Servlets, JSP, database connectivity, and application security.
Interested in learning more? Register for a Course Demo or visit the JustAcademy Official Website.
Additional Learning Resources